package com.zkthink.ceres.app.authority.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.zkthink.base.R;
import com.zkthink.base.request.PageParams;
import com.zkthink.cache.repository.CacheRepository;
import com.zkthink.ceres.app.authority.dto.*;
import com.zkthink.ceres.app.authority.service.AuthService;
import com.zkthink.ceres.common.annotations.LoginMode;
import com.zkthink.ceres.common.constant.CacheKey;
import com.zkthink.ceres.common.utils.ValidatorUtil;
import com.zkthink.ceres.member.dto.RelationAccountSearchDTO;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.member.vo.JumpWxaVo;
import com.zkthink.ceres.member.vo.MemberVO;
import com.zkthink.ceres.msgs.dao.CeresPushMsgsMapper;
import com.zkthink.ceres.msgs.service.CeresPushMsgsService;
import com.zkthink.ceres.msgs.service.MobilePushService;
import com.zkthink.ceres.sms.entity.SmsTask;
import com.zkthink.ceres.sms.enumeration.SourceType;
import com.zkthink.ceres.sms.enumeration.TemplateCodeType;
import com.zkthink.ceres.sms.service.SmsTaskService;
import com.zkthink.context.BaseContextHandler;
import com.zkthink.jwt.model.AuthInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.zkthink.ceres.applet.authority.config.AuthorityWebConfiguration.getMid;

/**
 * Created by kellen on 2020/5/3.
 */

@Slf4j
@Validated
@RestController
@RequestMapping("/auth")
@Api(value = "auth", tags = "鉴权服务")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private CacheRepository cacheRepository;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ApplicationContext context;

    @Autowired
    private SmsTaskService smsTaskService;
    @Autowired
    private MobilePushService mobilePushService;
    // @Value("${spring.profiles.active:prod}")
    protected String profiles = "prod";

    @Autowired
    private CeresPushMsgsMapper ceresPushMsgsMapper;

    @Autowired
    private CeresPushMsgsService ceresPushMsgsService;


    /**
     * app登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户名密码/验证码登录", notes = "用户名密码/验证码登录")
    public R<AuthInfo> login(HttpServletRequest request, @RequestBody @Validated CommonAppLoginDTO appLoginDTO) {
        System.out.println(appLoginDTO.getAccount());
        if (appLoginDTO == null) {
            return R.fail("账号或者密码错误");
        }

        if (StringUtils.isBlank(appLoginDTO.getPassWord()) && StringUtils.isBlank(appLoginDTO.getCode())) {
            return R.fail("密码和验证码至少输入一项");
        }
        return authService.login(request, appLoginDTO);

    }

    @PostMapping("/setRoleType")
    @ApiOperation(value = "设置用户类型", notes = "设置用户类型")
    public R setRoleType(@RequestBody @Validated SetRoleTypeDTO setRoleTypeDTO) {
        return authService.setRoleType(setRoleTypeDTO);
    }

    @PostMapping("/loginByAdmin")
    @ApiOperation(value = "pc端拟用户登录", notes = "pc端拟用户登录")
    public R<AuthInfo> loginByAdmin(@RequestBody @Validated CommonAppLoginDTO appLoginDTO) {
        if (appLoginDTO == null) {
            return R.fail("账号或者密码错误");
        }
        if (StringUtils.isBlank(appLoginDTO.getPassWord())) {
            return R.fail("密码未输入");
        }
        return authService.loginByAdmin(appLoginDTO);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "注册")
    public R register(@RequestBody RegDTO regDTO) throws Exception {
        log.info("注册信息:{}", regDTO);


        /**
         * 本机号码不需要验证码,输入的号码需要验证码
         */
        if (regDTO.getIsValidate()) {
            //短信验证码校验
            String key = CacheKey
                    .buildKey(CacheKey.REGISTER_USER, TemplateCodeType.CODE_REGISTER_USER.name(),
                            regDTO.getAccount());
            String code = cacheRepository.get(key);
            if (StrUtil.isBlank(code) || !code.equals(regDTO.getCode())) {
                return R.fail(code, "验证码错误");
            }
        }

        return authService.register(regDTO);
    }


    @PostMapping("/register/verify")
    @LoginMode(strict = false)
    @ApiOperation(value = "验证码发送", notes = "验证码发送")
    public R verify(@Validated @RequestBody VerifyDTO param) {


        if (!ValidatorUtil.checkPhone(param.getPhone())) {
            return R.fail("请填写正确格式手机号");
        }

        //判断手机号是否注册
        Member member = memberService.findByAccount(param.getPhone());
        if (null != member) {
            return R.validFail("手机号码已注册");
        }
        String code = "123456";
//        //判断是否是开发环境，开发环境不实际发送验证码
        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
            code = RandomUtil.randomNumbers(6);
            sendSmsUtil(code,param.getPhone(),"2174536");
        }
        //缓存验证码
        String key = CacheKey
                .buildKey(CacheKey.REGISTER_USER, TemplateCodeType.CODE_REGISTER_USER.name(),
                        param.getPhone());
        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
        return R.success();
    }

    /**
     * 添加核销人员验证码发送
     *
     * @param param
     * @return
     */
//    @PostMapping("/store/addverify")
//    @LoginMode(strict = false)
//    @ApiOperation(value = "添加核销人员验证码发送", notes = "添加核销人员验证码发送")
    public R addverify(@Validated @RequestBody VerifyDTO param) {


        if (!ValidatorUtil.checkPhone(param.getPhone())) {
            return R.fail("请填写正确格式手机号");
        }
        //判断手机号是否注册
        Member member = memberService.findByAccount(param.getPhone());
        if (member == null) {
            return R.validFail("手机号码未注册");
        } else if (member.getUserType() == 3) {
            return R.validFail("该用户已经是核销人员了");
        }

        String code = "123456";
        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//            sendSmsUtil(code,param.getPhone(),"2174536");
//        }
        //缓存验证码
        String key = CacheKey
                .buildKey(CacheKey.ADD_verify, TemplateCodeType.CODE_Add_verify.name(),
                        param.getPhone());
        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
        return R.success();
    }

    @PostMapping("/login/verify")
    @LoginMode(strict = false)
    @ApiOperation(value = "登录发送验证码", notes = "登录发送验证码")
    public R loginVerify(@Validated @RequestBody VerifyDTO param) {

        if (!ValidatorUtil.checkPhone(param.getPhone())) {
            return R.fail("请填写正确格式手机号");
        }
        //判断手机号是否注册
        Member member = memberService.findByAccount(param.getPhone());
        if (member == null) {
            return R.validFail("手机号码未注册");
        }
        String code = "123456";
        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//
//            //创建短信任务
//            sendSmsUtil(code,param.getPhone(),"2174536");
//            //app原代码
//            /*SmsTask smsTask = SmsTask.builder().build();
//            smsTask.setSourceType(SourceType.SERVICE);
//            smsTask.setTemplateParams(buildTemplateParam(code));
//            smsTask.setReceiver(param.getPhone());
//            smsTask.setDraft(false);
//            //验证码短信 默默人为通用类型
//            smsTaskService.saveTask(smsTask, TemplateCodeType.CODE_LOGIN_USER);*/
//        }


        //缓存验证码
        String key = CacheKey
                .buildKey(CacheKey.LOGIN_USER, TemplateCodeType.CODE_LOGIN_USER.name(),
                        param.getPhone());
        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
        return R.success();
    }

    @PostMapping("/updatePassword/verify")
    @LoginMode(strict = false)
    @ApiOperation(value = "修改密码发送验证码", notes = "修改密码发送验证码")
    public R updatePasswordVerify(@Validated @RequestBody VerifyDTO param) {

        if (!ValidatorUtil.checkPhone(param.getPhone())) {
            return R.fail("请填写正确格式手机号");
        }
        //判断手机号是否注册
        Member member = memberService.findByAccount(param.getPhone());
        if (member == null) {
            return R.validFail("手机号码未注册");
        }
        String code = "123456";
//        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//            sendSmsUtil(code,param.getPhone(),"2174536");
//        }
        //缓存验证码
        String key = CacheKey
                .buildKey(CacheKey.CODE_UPDATE_PASSWORD, TemplateCodeType.CODE_UPDATE_PASSWORD.name(),
                        param.getPhone());
        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
        return R.success();
    }


//    @PostMapping("/updatePayPassword/verify")
//    @LoginMode(strict = false)
//    @ApiOperation(value = "修改支付密码发送验证码", notes = "修改支付密码发送验证码")
//    public R updatePayPasswordVerify(@Validated @RequestBody VerifyDTO param) {
//        //判断手机号是否注册
//        Member member = memberService.findByAccount(param.getPhone());
//        if (member == null) {
//            return R.validFail("手机号码未注册");
//        }
//        String code = "123456";
//        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//            SmsTask smsTask = SmsTask.builder().build();
//            smsTask.setSourceType(SourceType.SERVICE);
//            smsTask.setTemplateParams(buildTemplateParam(code));
//            smsTask.setReceiver(param.getPhone());
//            smsTask.setDraft(false);
//            //验证码短信 默默人为通用类型
//            smsTaskService.saveTask(smsTask, TemplateCodeType.CODE_UpdatePayPass);
//        }
//        //缓存验证码
//        String key = CacheKey
//                .buildKey(CacheKey.UpdatePayPassword_User, TemplateCodeType.CODE_UpdatePayPass.name(),
//                        param.getPhone());
//        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
//        return R.success();
//    }

//    @PostMapping("/updatePhone/verify")
//    @LoginMode(strict = false)
//    @ApiOperation(value = "修改手机号发送验证码", notes = "修改手机号发送验证码")
//    public R updatePhoneVerify(@Validated @RequestBody VerifyDTO param) {
//
//        if (!ValidatorUtil.checkPhone(param.getPhone())) {
//            return R.fail("请填写正确格式手机号");
//        }
//        //判断手机号是否注册
//        Member member = memberService.findByAccount(param.getPhone());
////        if (member != null) {
////            return R.validFail("手机号码已注册");
////        }
//        String code = "123456";
//        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//            SmsTask smsTask = SmsTask.builder().build();
//            smsTask.setSourceType(SourceType.SERVICE);
//            smsTask.setTemplateParams(buildTemplateParam(code));
//            smsTask.setReceiver(param.getPhone());
//            smsTask.setDraft(false);
//            //验证码短信 默默人为通用类型
//            smsTaskService.saveTask(smsTask, TemplateCodeType.CODE_UpdatePhone);
//        }
//        //缓存验证码
//        String key = CacheKey
//                .buildKey(CacheKey.UpdatePhone_User, TemplateCodeType.CODE_UpdatePhone.name(),
//                        param.getPhone());
//        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
//        return R.success();
//    }


//    @PostMapping("/updatePhone/update")
//    @LoginMode(strict = false)
//    @ApiOperation(value = "修改手机号", notes = "修改手机号")
//    public R<AuthInfo> updatePhoneByUpDATE(@RequestBody MiniAppPhoneDTO param) {
//
//        Long mid = BaseContextHandler.getUserId();
//        param.setMid(mid);
//
//        //判断手机号是否注册
//        Member member = memberService.findByAccount(param.getAccount());
//        if (member != null) {
//            return R.validFail("手机号码已注册");
//        }
//        String key = CacheKey
//                .buildKey(CacheKey.UpdatePhone_User, TemplateCodeType.CODE_UpdatePhone.name(),
//                        param.getAccount());
//        String code = cacheRepository.get(key);
//        if (StrUtil.isBlank(code) || !code.equals(param.getCode())) {
//            return R.validFail("验证码错误");
//        }
//
//        return authService.bindPhoneByCode(param);
//    }


    private String buildTemplateParam(String code) {
        JSONObject param = new JSONObject();
        param.put("code", code);
        return param.toString();
    }


    /**
     * 微信小程序登录
     */
    @PostMapping("/wx/miniApp")
    @ApiOperation(value = "微信小程序登录", notes = "微信小程序登录")
    public R<AuthInfo> miniApp(HttpServletRequest request, @RequestBody MiniAppLoginDTO miniAppLoginDTO) {
        log.info("小程序登录入参信息:{}", miniAppLoginDTO);
        return authService.loginByWxMa(request,miniAppLoginDTO);
    }

    @ApiOperation(value = "微信小程序登录2.0", notes = "微信小程序登录2.0")
    @PostMapping("/wx/miniApp/bindPhone")
    public R<AuthInfo> wx(@RequestBody MiniAppLoginDTO miniAppLoginDTO) {
        log.info("小程序登录入参信息:{}", miniAppLoginDTO);
        return authService.loginByWx(miniAppLoginDTO);
    }

    @PostMapping("/wx/bindPhone")
    @ApiOperation(value = "绑定手机号", notes = "绑定手机号")
    public R<AuthInfo> bindPhone(@RequestBody MiniAppAuthDTO miniAppAuthDTO) {
        return authService.bindPhone(getMid(), miniAppAuthDTO);
    }

    @GetMapping("/updateCity/{city}")
    @ApiOperation(value = "绑定手机号", notes = "绑定手机号")
    public R updateCity(@PathVariable String city) {
        Member member = memberService.selectById(getMid());
        if (member == null) {
            return R.fail("无当前用户信息");
        }
        member.setCity(city);
        return memberService.updateById(member) ? R.success("修改成功") : R.fail("操作失败");
    }

    @ApiOperation(value = "获取加密scheme码", notes = "获取加密scheme码")
    @PostMapping("/generateScheme")
    public R generateScheme(@RequestBody JumpWxaVo jumpWxaVo) {

        return R.success(authService.generateScheme(jumpWxaVo));
    }

    /**
     * 微信登录app
     */
    @PostMapping("/wx/appLogin")
    @ApiOperation(value = "微信登录app,当返回的账户值为空的时候,提示绑定电话", notes = "微信登录app")
    public R<AuthInfo> appLogin(@RequestBody MiniAppLoginDTO miniAppLoginDTO) throws Exception {
        log.info("微信app登录入参信息:{}", miniAppLoginDTO);
        return authService.loginAppByWxMa(miniAppLoginDTO);
    }

    /**
     * 通过验证码绑定微信用户电话
     */
    @PostMapping("/app/bindPhoneByCode")
    @ApiOperation(value = "微信app登录通过验证码绑定用户电话", notes = "微信app登录通过验证码绑定用户电话")
    public R<AuthInfo> appBindPhoneByCode(@RequestBody MiniAppPhoneDTO regDTO) {
        log.info("注册信息:{}", regDTO);
        //短信验证码校验
        String key = CacheKey
                .buildKey(CacheKey.REGISTER_USER, TemplateCodeType.CODE_REGISTER_USER.name(),
                        regDTO.getAccount());
        String code = cacheRepository.get(key);
        if (StrUtil.isBlank(code) || !code.equals(regDTO.getCode())) {
            return R.validFail("验证码错误");
        }
        if (!regDTO.getPassWord().equals(regDTO.getConfirPassWord())) {
            return R.validFail("密码输入不一致");
        }
        return authService.appBindPhoneByCode(regDTO);
    }

    /**
     * 获取openid
     */
    @PostMapping("/app/getOpenidByCode")
    @ApiOperation(value = "获取openid", notes = "获取openid")
    public R<String> getOpenidByCode(@RequestBody MiniAppLoginDTO regDTO) throws IOException {
        return authService.getOpenidByCode(regDTO);
    }


    /**
     * 通过验证码绑定微信用户电话
     */
    @PostMapping("/wx/bindPhoneByCode")
    @ApiOperation(value = "通过验证码绑定用户电话", notes = "通过验证码绑定用户电话")
    public R<AuthInfo> bindPhoneByCode(@RequestBody MiniAppPhoneDTO regDTO) {
        log.info("注册信息:{}", regDTO);
        //短信验证码校验
        String key = CacheKey
                .buildKey(CacheKey.REGISTER_USER, TemplateCodeType.CODE_REGISTER_USER.name(),
                        regDTO.getAccount());
        String code = cacheRepository.get(key);
        if (StrUtil.isBlank(code) || !code.equals(regDTO.getCode())) {
            return R.validFail("验证码错误");
        }
        return authService.bindPhoneByCode(regDTO);
    }

    /**
     * 绑定微信用户信息
     */
    @PostMapping("/wx/bindWxUserInfo")
    @ApiOperation(value = "绑定微信用户信息", notes = "绑定微信用户信息")
    public R<MemberVO> bindWxUserInfo(@RequestBody MiniAppAuthDTO miniAppAuthDTO) {
        log.info("绑定微信用户信息入参:{}", miniAppAuthDTO);
        return authService.bindWxUserInfo(miniAppAuthDTO);
    }


    @PostMapping("/updatePassword")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public R update(@RequestBody CommonAppLoginDTO commonAppLoginDTO) {
        if (commonAppLoginDTO == null) {
            return R.fail("账号或者密码错误");
        }
        if (StringUtils.isBlank(commonAppLoginDTO.getPassWord()) || StringUtils.isBlank(commonAppLoginDTO.getCode())) {
            return R.fail("密码或者验证码未输入");
        }


        log.info("用户名修改密码入参信息:{}", commonAppLoginDTO);
        //短信验证码校验
        String key = CacheKey
                .buildKey(CacheKey.CODE_UPDATE_PASSWORD, TemplateCodeType.CODE_UPDATE_PASSWORD.name(),
                        commonAppLoginDTO.getAccount());
        String code = cacheRepository.get(key);
        if (StrUtil.isBlank(code) || !code.equals(commonAppLoginDTO.getCode())) {
            return R.validFail("验证码错误");
        }


        return authService.update(commonAppLoginDTO);
    }


    /**
     * 注销的账户前拼接字段
     *
     * @return
     */
    @PostMapping("/logOff")
    @ApiOperation(value = "注销账户", notes = "注销账户")
    public R logOffAccount() {
        Long mid = BaseContextHandler.getUserId();
        return authService.logOffAccount(mid);
    }

    /**
     * 注销的账户前拼接字段
     *
     * @return
     */
    @PostMapping("/logOut")
    @ApiOperation(value = "退出登录", notes = "退出登录")
    public R logOutAccount() {
        Long mid = BaseContextHandler.getUserId();
        return authService.logOutAccount(mid);
    }

//    @PostMapping("/Store/verify")
//    @LoginMode(strict = false)
//    @ApiOperation(value = "申请实体店验证码发送", notes = "验证码发送")
//    public R Store(@Validated @RequestBody VerifyDTO param) {
//        if (!ValidatorUtil.checkPhone(param.getPhone())) {
//            return R.fail("请填写正确格式手机号");
//        }
//        String code = "123456";
//        //判断是否是开发环境，开发环境不实际发送验证码
//        if (StrUtil.isNotBlank(profiles) && !"dev".equals(profiles)) {
//            code = RandomUtil.randomNumbers(6);
//            //创建短信任务
//            SmsTask smsTask = SmsTask.builder().build();
//            smsTask.setSourceType(SourceType.SERVICE);
//            smsTask.setTemplateParams(buildTemplateParam(code));
//            smsTask.setReceiver(param.getPhone());
//            smsTask.setDraft(false);
//            //验证码短信 默默人为通用类型
//            smsTaskService.saveTask(smsTask, TemplateCodeType.CODE_Store_Verification);
//        }
//        //缓存验证码
//        String key = CacheKey
//                .buildKey(CacheKey.REGISTER_USER, TemplateCodeType.CODE_Store_Verification.name(),
//                        param.getPhone());
//        cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
//        return R.success();
//    }

    /**
     * app店铺登录
     */
    @PostMapping("/shopLogin")
    @ApiOperation(value = "实体店登录", notes = "实体店登录")
    public R<AuthInfo> shopLogin(@RequestBody @Validated CommonAppLoginDTO appLoginDTO) {
        if (appLoginDTO == null) {
            return R.fail("账号或者密码错误");
        }
        if (StringUtils.isBlank(appLoginDTO.getPassWord())) {
            return R.fail("密码未输入");
        }
        return authService.shopLogin(appLoginDTO);
    }


    @PostMapping("/addRelationAccount")
    @ApiOperation(value = "添加关联账户并登陆", notes = "添加关联账户并登陆")
    public R<AuthInfo> addRelationAccount(HttpServletRequest request, @RequestBody @Validated CommonAppLoginDTO appLoginDTO) {
        return authService.addRelationAccount(request, appLoginDTO);
    }

    @GetMapping("/deleteRelationAccount/{id}")
    @ApiOperation(value = "删除关联账户", notes = "删除关联账户")
    public R deleteRelationAccount(@PathVariable("id") Long id) {
        return authService.deleteRelationAccount(id);
    }

    @GetMapping("/appOneLoginSetRoleType/{roleType}")
    @ApiOperation(value = "app第一次登录设置角色类型", notes = "app第一次登录设置角色类型")
    public R appOneLoginSetRoleType(@PathVariable("roleType") Integer roleType) {
        return authService.appOneLoginSetRoleType(roleType);
    }


    @PostMapping("/searchRelationAccount")
    @ApiOperation(value = "查询关联账户", notes = "查询关联账户")
    public R<IPage<RelationAccountSearchDTO>> searchRelationAccount(@RequestBody PageParams<Long> params) {
        Long mid = BaseContextHandler.getUserId();
        IPage page = params.getPage();
        return authService.searchRelationAccount(page, mid);
    }


    @GetMapping("/loginRelationAccount/{id}")
    @ApiOperation(value = "切换关联账户", notes = "切换关联账户")
    public R<AuthInfo> loginRelationAccount(@PathVariable("id") Long id) {
        return authService.loginRelationAccount(id);
    }

    private String sendSmsUtil(String code, String phone, String templateID) {

        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential credential = new Credential("AKIDSnFg0EORH2g9i5FBuPjphMC1mNp4B904", "Bdv2w12sX2LSO8h4FG5Yt7FBwkYCf");
            //创建http连接
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            httpProfile.setConnTimeout(60);
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            //实例化客户端对象
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(credential, "ap-guangzhou", clientProfile);

            //实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
            SendSmsRequest req = new SendSmsRequest();

            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看

            req.setSmsSdkAppid("1400910943");

            /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
            req.setSign("三事堂健康产业");
            /* 模板 ID: 必须填写已审核通过的模板 ID */
            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
            req.setTemplateID(templateID);

            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
            String[] templateParamSet = {code};
            req.setTemplateParamSet(templateParamSet);

            /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
             * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号 */
            String[] phoneNumberSet = {"+86" + phone};
            req.setPhoneNumberSet(phoneNumberSet);

            /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
            String sessionContext = "";
            req.setSessionContext(sessionContext);

            /* 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手] */
            String extendCode = "";
            req.setExtendCode(extendCode);

            /* 国际/港澳台短信 SenderId（无需要可忽略）: 国内短信填空，默认未开通，如需开通请联系 [腾讯云短信小助手] */
            String senderid = "";
            req.setSenderId(senderid);


            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
             * 返回的 res 是一个 SendSmsResponse 类的实例，与请求对象对应 */
            SendSmsResponse res = client.SendSms(req);

            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(res) + "验证码：==" + code);
            //} catch (TencentCloudSDKException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }
}
